import datetime
from flask import request, jsonify, current_app, g
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity, get_jwt
from werkzeug.security import check_password_hash
from app.models import Admin, AdminLog, Role
from app.core.extensions import db
from . import admin_blueprint


@admin_blueprint.route('/login', methods=['POST'])
def login():
    """管理员登录API"""
    data = request.json
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'code': 1, 'message': '用户名和密码不能为空'}), 400

    admin = Admin.query.filter_by(username=username).first()

    if admin and admin.check_password(password):
        # 获取管理员角色和权限
        roles = [role.name for role in admin.roles] if admin.roles else []
        # 生成JWT令牌
        access_token = create_access_token(
            identity=str(admin.id),  # 将管理员ID转换为字符串
            additional_claims={  # 使用 additional_claims 存储额外信息
                'username': admin.username,
                'role': admin.role,
                'roles': roles,
                'is_tenant': admin.is_tenant,
                'tenant_id': admin.tenant_id,
                'is_test': admin.is_test
            },
            expires_delta=datetime.timedelta(days=1)
        )

        # 更新登录时间
        admin.last_login = datetime.datetime.now()
        # 记录登录日志
        log = AdminLog(
            admin_id=admin.id,
            action='登录',
            ip=request.remote_addr,
            details='管理员登录',
            tenant_id=admin.tenant_id
        )

        db.session.add(log)
        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '登录成功',
            'data': {
                'token': access_token,
                'admin': {
                    'id': admin.id,
                    'username': admin.username,
                    'email': admin.email,
                    'role': admin.role,
                    'roles': roles,
                    'is_tenant': admin.is_tenant,
                    'tenant_id': admin.tenant_id,
                    'is_test': admin.is_test
                }
            }
        })

    return jsonify({'code': 1, 'message': '用户名或密码错误'}), 401


@admin_blueprint.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前管理员信息"""
    current_user_id = get_jwt_identity()  # 获取管理员ID
    claims = get_jwt()  # 获取token中的额外信息

    admin = Admin.query.get(current_user_id)
    if not admin:
        return jsonify({'code': 1, 'message': '管理员不存在'}), 404

    # 获取角色名称列表
    roles = [role.name for role in admin.roles] if admin.roles else []

    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': {
            'id': admin.id,
            'username': admin.username,
            'email': admin.email,
            'role': admin.role,
            'roles': roles,
            'is_tenant': admin.is_tenant,
            'tenant_id': admin.tenant_id,
            'is_test': admin.is_test,
            'last_login': admin.last_login.strftime('%Y-%m-%d %H:%M:%S') if admin.last_login else None
        }
    })


@admin_blueprint.route('/profile', methods=['PUT', 'POST'])
@jwt_required()
def update_profile():
    """更新管理员个人信息"""
    current_user_id = get_jwt_identity()  # 获取管理员ID

    admin = Admin.query.get(current_user_id)
    if not admin:
        return jsonify({'code': 1, 'message': '管理员不存在'}), 404

    data = request.json
    email = data.get('email')
    old_password = data.get('old_password')
    new_password = data.get('new_password')

    # 如果提供了新密码，需要验证旧密码
    if new_password:
        if not old_password or not admin.check_password(old_password):
            return jsonify({'code': 1, 'message': '原密码错误'}), 400
        admin.set_password(new_password)

    # 更新邮箱
    if email:
        admin.email = email

    # 记录操作日志
    log = AdminLog(
        admin_id=admin.id,
        action='更新个人信息',
        ip=request.remote_addr,
        details='管理员更新个人信息'
    )

    db.session.add(log)
    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功'
    })


@admin_blueprint.route('/user-info', methods=['GET'])
@jwt_required()
def get_user_info():
    """获取当前用户信息 (包括权限和角色)"""
    current_user_id = get_jwt_identity()

    admin = Admin.query.get(current_user_id)
    if not admin:
        return jsonify({'code': 1, 'message': '管理员不存在'}), 404

    # 获取角色名称列表
    roles = [role.name for role in admin.roles] if admin.roles else []
    # 获取权限列表
    permissions = admin.get_permissions()

    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': {
            'id': admin.id,
            'username': admin.username,
            'email': admin.email,
            'role': admin.role,
            'roles': roles,
            'permissions': permissions,
            'is_tenant': admin.is_tenant,
            'tenant_id': admin.tenant_id,
            'is_test': admin.is_test
        }
    })


@admin_blueprint.route('/logout', methods=['GET', 'POST'])
@jwt_required()
def logout():
    """管理员登出"""
    current_user_id = get_jwt_identity()  # 获取管理员ID

    # 记录登出日志
    log = AdminLog(
        admin_id=current_user_id,
        action='登出',
        ip=request.remote_addr,
        details='管理员登出'
    )

    db.session.add(log)
    db.session.commit()

    # 前端需要清除本地存储的token
    return jsonify({
        'code': 0,
        'message': '登出成功'
    })
